<?php

class AdminUserService extends FServiceBase
{    
    /**
    * Get a User model given its ID
    * 
    * @param int id User ID
    * @return FServiceModel
    */    
    public function save($params) {
        /*if ($params['User']['password'] == '') {
            unset($params['User']['password']);
            unset($params['User']['confirmPassword']);
        }*/
        
        $model = $this->getModel($params['User'],'User');
        $this->result->processed('model', $model);
        
        $isNewRecord = $model->isNewRecord;
        
        $passwordForSend = '';
        if ($isNewRecord || (isset($params['User']['password']) && $params['User']['password'] != ''))
        {
            $model->confirmPassword = md5($params['User']['confirmPassword']);
            $model->password = md5($params['User']['password']);
            if ($isNewRecord)
                $passwordForSend = $params['User']['password'];    
        }
        
        $updatedAttrs = array('username','email');
        if ($isNewRecord)
        {
            $model->setScenario('create_admin_user');
            $model->status = User::STATUS_DEACTIVE;
            $model->validation_type = User::REGISTER_VALIDATION_TYPE;
            $model->validation_code = md5(randomString('lower',8));
            $model->created_date = date('Y-m-d');
        }
        else
        {
            $model->setScenario('update_admin_user');
            if (isset($params['User']['password']) && $params['User']['password'] != '')
                $updatedAttrs[] = 'password';        
        }
        
        if (! $model->validate())
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('User.User', 'Submitted data is missing or invalid.'));
        elseif ($this->getParam($params, 'validateOnly',0) == TRUE)
            return $this->result;
        else
        {
            if ($isNewRecord)
            {
                if (!$model->save())
                    $this->result->fail(ERROR_HANDLING_DB, Yii::t('User.User','Error while saving submitted data into database.'));
                else
                {
                    // assign admin role
                    Yii::app()->authManager->assign('administrators',$model->id);
                    // send mail to new account user
                    $adminEmail = trim(SiteSettings::CONTACT_EMAIL);   
                    Yii::import('Core.extensions.vendors.mail.YiiMailMessage');
                    Yii::app()->mail->viewPath = 'application.modules.User.views.mail';
                    $message = new YiiMailMessage;
                    $message->view = 'send_validation_code_to_new_admin';
                    $message->setSubject('[International Environment Company] Welcome to Admin Panel of IEC Website');
                    $message->setBody(array(
                        'model' => $model,
                        'passwordForSend' => $passwordForSend,
                        ), 'text/html');
                    $message->addFrom($adminEmail, 'IEC Admin Panel');
                    $message->addTo($model->email, $model->username);
                    Yii::app()->mail->send($message);
                }
            }
            else
            {
                if (!$model->update($updatedAttrs))
                    $this->result->fail(ERROR_HANDLING_DB, Yii::t('User.User','Error while saving submitted data into database.'));    
            }
        }
        
        return $this->result;
    }

    public function forgotPassword($params) {        
        if (!isset($params['User']['email']))
            return $this->result->fail(1, 'Email is missing.');
        $model = User::model()->find('email=:email AND status=:status',array(':email'=>$params['User']['email'],':status'=>User::STATUS_ACTIVE));
        if (is_null($model))
            return $this->result->fail(2, 'User with this e-mail is not found');
        
        $model->validation_type = User::FORGOT_PASSWORD_VALIDATION_TYPE;
        $model->validation_code = md5(randomString('lower',8));
        if ($model->update(array('validation_type','validation_code')))
        {
            // send mail to user
            $adminEmail = trim(SiteSettings::CONTACT_EMAIL);   
            Yii::import('Core.extensions.vendors.mail.YiiMailMessage');
            Yii::app()->mail->viewPath = 'application.modules.User.views.mail';
            $message = new YiiMailMessage;
            $message->view = 'confirm_reset_password';
            $message->setSubject('[International Environment Company] Confirmation for reseting your password');
            $message->setBody(array(
                'model' => $model,
                ), 'text/html');
            $message->addFrom($adminEmail, 'IEC Admin Panel');
            $message->addTo($model->email, $model->username);
            Yii::app()->mail->send($message);
        }
        else
            $this->result->fail(3, 'confirm forgot password is failed.');
        return $this->result;
    }
    
    public function resetPassword($params) {        
        $model = $params['user'];
        if (!is_object($model))
            return $this->result->fail(1, 'User is not found.');
        $passwordForSend = randomString('lower',8);
        $model->password = md5($passwordForSend);
        $model->validation_type = 0;
        $model->validation_code = '';
        if ($model->update(array('password','validation_type','validation_code')))
        {
            // send mail to user
            $adminEmail = trim(SiteSettings::CONTACT_EMAIL);   
            Yii::import('Core.extensions.vendors.mail.YiiMailMessage');
            Yii::app()->mail->viewPath = 'application.modules.User.views.mail';
            $message = new YiiMailMessage;
            $message->view = 'password_is_reset';
            $message->setSubject('[International Environment Company] Your password is reset');
            $message->setBody(array(
                'model' => $model,
                'passwordForSend' => $passwordForSend,
                ), 'text/html');
            $message->addFrom($adminEmail, 'IEC Admin Panel');
            $message->addTo($model->email, $model->username);
            Yii::app()->mail->send($message);
        }
        else
            $this->result->fail(3, 'confirm forgot password is failed.');
        return $this->result;
    }
}
